<template>
  <zeda-dialog
    v-model="visible"
    :title="(id <= 0 ? '新建' : '编辑') + ''"
    width="1000px"
    :before-close="handleClose"
  >
    <h2 class="title">用能预算申报表</h2>
    <el-form ref="form" :model="model" :rules="rules" label-width="0">
      <el-form-item label="编号" prop="no" label-width="350px">
        <el-input
          v-model.trim="model.no"
          placeholder="请输入编号"
          maxlength="20"
          style="width: 300px"
        ></el-input>
      </el-form-item>
      <el-descriptions :column="2" border class="form">
        <el-descriptions-item label="申报单位">
          {{ userInfo.deptName }}
        </el-descriptions-item>
        <el-descriptions-item label="联系人">
          <el-form-item prop="contact">
            <el-input
              v-model="model.contact"
              placeholder="请输入联系人"
              @input="btKeyCn"
              maxlength="8"
            ></el-input> </el-form-item
        ></el-descriptions-item>
        <el-descriptions-item label="单位地址">
          <el-form-item prop="unitAddress">
            <el-input
              v-model="model.unitAddress"
              placeholder="请输入单位地址"
              maxlength="100"
              @input="btKeyUp"
            ></el-input> </el-form-item
        ></el-descriptions-item>
        <el-descriptions-item label="联系电话">
          <el-form-item prop="contactNumber">
            <el-input
              v-model="model.contactNumber"
              placeholder="请输入联系电话"
              maxlength="11"
            ></el-input>
          </el-form-item>
        </el-descriptions-item>
        <el-descriptions-item label="填报类型" :span="2">
          <el-form-item>
            <el-checkbox
              v-for="(dict, i) in model.typeConfigRecordRequests"
              :key="i"
              :checked="dict.isSelected == 1"
              @change="(val) => selectDeclareType(val, dict)"
            >
              {{ dict.typeName }}</el-checkbox
            >
          </el-form-item></el-descriptions-item
        >
      </el-descriptions>
      <template
        v-if="
          model.typeConfigRecordRequests &&
          model.typeConfigRecordRequests.length > 0
        "
      >
        <el-descriptions
          v-for="(item, index) in model.typeConfigRecordRequests"
          :key="index"
          :column="2"
          border
          class="form"
        >
          <template v-if="item.isSelected == 1">
            <el-descriptions-item label="用能事由" :span="2">
              <el-form-item
                :label="item.typeName"
                prop="isIncrease"
                label-width="120px"
              >
                <el-radio-group
                  v-model="item.isIncrease"
                  @change="(value) => getAmount(value, item)"
                >
                  <el-radio :label="1">增加</el-radio>
                  <el-radio :label="0">减少</el-radio>
                </el-radio-group>
              </el-form-item></el-descriptions-item
            >
            <el-descriptions-item :label="item.energyObjectName" :span="2">
              <el-form-item>
                <el-checkbox
                  v-for="dict in item.configItemRecordRequests"
                  :key="dict.name"
                  :checked="dict.isSelected == 1"
                  @change="(val) => change(val, dict)"
                >
                  {{ dict.name }}</el-checkbox
                >
              </el-form-item></el-descriptions-item
            >
            <el-descriptions-item :label="item.energyBudgetName" :span="2">
              <el-form-item
                v-if="item.isUseStandard == 1"
                label="标准"
                :prop="'typeConfigRecordRequests[' + index + '].standardFee'"
                :rules="[
                  {
                    required: true,
                    message: `请输入标准`,
                    trigger: ['blur', 'change'],
                  },
                ]"
                label-width="160px"
              >
                <el-input
                  v-model="item.standardFee"
                  maxlength="11"
                  placeholder="请输入"
                  @input="(value) => keyFixAmount(value, 'standardFee')"
                  @blur="(value) => getAmount(value, item)"
                >
                  <template slot="append">{{
                    item.standardUnit
                  }}</template></el-input
                >
              </el-form-item>
              <div
                v-for="(it, idx) in item.configItemRecordRequests"
                :key="idx"
                class="flex"
              >
                <el-form-item
                  v-if="it.isSelected == 1"
                  :label="it.name"
                  :prop="
                    'typeConfigRecordRequests[' +
                    index +
                    '].configItemRecordRequests[' +
                    idx +
                    '].value'
                  "
                  :rules="[
                    {
                      required: true,
                      message: `请输入${it.name}`,
                      trigger: ['blur', 'change'],
                    },
                  ]"
                  label-width="160px"
                >
                  <el-input
                    v-model="it.value"
                    maxlength="11"
                    placeholder="请输入"
                    @blur="(value) => getAmount(value, item)"
                  >
                    <template slot="append">{{
                      item.energyUnit
                    }}</template></el-input
                  >
                </el-form-item>
                <el-form-item
                  v-if="it.isSelected == 1"
                  label="是否计算费用"
                  :prop="
                    'typeConfigRecordRequests[' +
                    index +
                    '].configItemRecordRequests[' +
                    idx +
                    '].isCalculate'
                  "
                  label-width="120px"
                >
                  <el-radio-group v-model="it.isCalculate">
                    <el-radio :label="1">是</el-radio>
                    <el-radio :label="0">否</el-radio>
                  </el-radio-group>
                </el-form-item>
              </div>
            </el-descriptions-item>
          </template>
        </el-descriptions>
        <el-descriptions :column="2" border class="form">
          <el-descriptions-item label="用能预算利用时间" :span="2">
            <el-form-item prop="year">
              <el-date-picker
                v-model="model.year"
                type="year"
                placeholder="请选择"
                value-format="yyyy"
              >
              </el-date-picker>
              1月1日至12月31日
            </el-form-item></el-descriptions-item
          >
          <el-descriptions-item label="申请用能预算经费" :span="2">
            合计： {{ model.budgetFund }} 元
          </el-descriptions-item>
        </el-descriptions>
      </template>
    </el-form>
    <form-button slot="footer" @cancel="handleClose" @submit="submit">
    </form-button>
  </zeda-dialog>
</template>

<script>
import { mapState } from "vuex";
import {
  detail,
  add,
  edit,
  typeConfigTemplate,
  getBudgetFund,
} from "@/api/work/budgetDeclaration";
import { getByDeptId, getUserListByDept } from "@/api/departmental/index";
import FormButton from "@/components/FormButton";
import {
  replaceDigit,
  replaceInteger,
  accAdd,
  subtr,
  mul,
} from "@/utils/index";

export default {
  dicts: ["energy_declare_type", "energy_identify_types"],
  components: {
    FormButton,
  },
  props: {
    id: {
      type: [Number, String],
      default: "",
    },
    visible: {
      type: Boolean,
      default: false,
    },
  },
  computed: {
    ...mapState({
      userInfo: (state) => state.user,
    }),
  },
  data() {
    return {
      deptPeopleArr: [],
      loading: false, // 按钮加载中判断
      model: {
        budgetFund: 0,
        no: "",
        identifyTypes: [],
        contact: "",
        contactNumber: "",
        reason: "",
        unitAddress: "",
        permanentStaffNum: 0,
        temporaryNum: 0,
        otherPeopleNum: 0,
        officerOnSecondmentNum: 0,
        year: "",
        typeConfigRecordRequests: [],
      },
      rules: {
        no: [
          {
            required: true,
            message: "请输入编号",
            trigger: "blur",
          },
        ],
        unitAddress: [
          {
            required: true,
            message: "请输入单位地址",
            trigger: "blur",
          },
        ],
        contact: [
          {
            required: true,
            message: "请输入联系人",
            trigger: ["blur", "change"],
          },
        ],
        identifyTypes: [
          {
            required: true,
            message: "请选择",
            trigger: "change",
          },
        ],
        reason: [
          {
            required: true,
            message: "请输入用能事由",
            trigger: "blur",
          },
        ],
        typeConfigRecordRequests: [
          {
            required: true,
            message: "请选择填报类型",
            trigger: "change",
          },
        ],
        year: [
          {
            required: true,
            message: "请选择用能预算利用时间",
            trigger: "change",
          },
        ],
        contactNumber: [
          {
            required: true,
            pattern: /^1[3|4|5|6|7|8|9][0-9]\d{8}$/,
            message: "请输入正确的联系电话",
            trigger: "blur",
          },
        ],
      },
    };
  },
  watch: {
    visible(value) {
      if (value) {
        if (String(this.id).length > 0) {
          this.getInfo();
        } else {
          this.getPeopleList();
          this.getDeptmsg();
          setTimeout(() => {
            this.getTypeConfigTemplate();
          }, 1000);
        }
      }
    },
    // model: {
    //   handler(newVal, oldVal) {
    //     const that = this;
    //     let num = 0;
    //     newVal.typeConfigRecordRequests.map((item) => {
    //       if (item.isSelected == 1) {
    //         item.configItemRecordRequests.map((it) => {
    //           if (it.isCalculate == 1) {
    //             if (item.isIncrease == 1) {
    //               if (item.isUseStandard == 1) {
    //                 num = accAdd(num, it.value);
    //                 num = mul(Number(num), Number(item.standardFee ?? 0));
    //               } else {
    //                 num = accAdd(num, it.value);
    //               }
    //             } else {
    //               if (item.isUseStandard == 1) {
    //                 num = subtr(num, it.value);
    //                 num = mul(Number(num), Number(item.standardFee ?? 0));
    //               } else {
    //                 num = subtr(num, it.value);
    //               }
    //             }
    //           }
    //         });
    //       }
    //     });
    //     that.model.budgetFund = num;
    //   },
    //   deep: true, // 加这个属性，深度监听
    //   immediate: true,
    // },
  },
  methods: {
    getPeopleList() {
      this.deptPeopleArr = [];
      let params = {
        deptId: this.$store.state.user.deptId,
      };
      getUserListByDept(params)
        .then((res) => {
          if (res.code === 700) {
            this.$message.warning(res.msg);
            return false;
          }
          let arr = res?.data ?? [];
          if (arr.length > 0) {
            arr.map((item) => {
              let obj = {
                label: item?.nickName ?? "未知用户昵称",
                value: item?.userId ?? 1,
              };
              this.deptPeopleArr.push(obj);
            });
          }
        })
        .catch(() => {
          // this.$message.error("系统错误,请联系管理员!200380");
        });
    },
    getDeptmsg() {
      getByDeptId({
        deptId: this.$store.state.user.deptId,
      })
        .then((res) => {
          if (res.code === 700) {
            this.$message.warning(res.msg);
            return false;
          }
          this.info = res?.data ?? {};
        })
        .catch(() => {
          // this.$message.error("系统错误,请联系管理员!200370");
        });
    },
    getAmount(val, data) {
      if (data.isUseStandard == 1 && !data.standardFee) {
        // this.$message.warning("标准系数填写异常!");
        return false;
      }
      getBudgetFund({
        typeConfigRecordRequests: this.model.typeConfigRecordRequests,
      })
        .then((res) => {
          if (res.code === 700) {
            this.$message.warning(res.msg);
            return false;
          }
          this.model.budgetFund = res.data;
        })
        .catch(() => {
          // this.$message.error("系统错误,请联系管理员!");
        });
    },
    change(val, row) {
      row.isSelected = val == true ? 1 : 0;
    },
    selectDeclareType(val, row) {
      row.isSelected = val == true ? 1 : 0;
      if (!val) {
        this.model.identifyTypes = [];
        this.model.typeConfigRecordRequests.map((item) => {
          if (row.typeName == item.typeName) {
            item.configItemRecordRequests.map((it) => {
              it.isSelected = 0;
              it.value = "";
              return it;
            });
          }
        });
      }
    },
    getTypeConfigTemplate() {
      const that = this;
      typeConfigTemplate()
        .then((res) => {
          if (res.code === 700) {
            this.$message.warning(res.msg);
            return false;
          }
          that.model.contact = that.targetName(
            that.info.statisticsPersonId,
            that.deptPeopleArr
          );
          that.model.unitAddress = that.info.companyAddressProvince;
          that.model.contactNumber = that.info.statisticsPersonMobilePhone;
          that.model.typeConfigRecordRequests = res.data.map((item) => {
            item.configItemRecordRequests = item.typeConfigItemRecordVos;
            return item;
          });
        })
        .catch(() => {
          // this.$message.error("系统错误,请联系管理员!");
        });
    },
    targetName(id, arr) {
      let data = arr.find((item) => item.value == id);
      let name = "";
      if (data) {
        name = data.label;
      }
      return name;
    },
    btKeyUp(value) {
      this.model.unitAddress = value.replace(
        /[`~!@#$%^&*()_\-+=<>?:"{}|,.\/;'\\[\]·~！@#￥%……&*（）——\-+={}|《》？：“”【】、；‘’，。、]/g,
        ""
      );
    },
    btKeyCn(value) {
      this.model.contact = value.replace(/[^\u4e00-\u9fa5]/g, "");
    },
    keyFixAmount(value, key) {
      if (key == "standardFee") {
        this.model[key] = replaceDigit(value, 2);
      } else {
        this.model[key] = replaceInteger(value);
      }
    },
    getInfo() {
      const that = this;
      detail(this.id)
        .then((res) => {
          if (res.code === 700) {
            this.$message.warning(res.msg);
            return false;
          }
          that.model = { ...that.model, ...res.data };
          that.model.identifyTypes = [];
          that.model.year = res.data.year + "";
          this.model.typeConfigRecordRequests =
            res.data.typeConfigRecordVos.map((item) => {
              item.configItemRecordRequests = item.typeConfigItemRecordVos;
              return item;
            });
        })
        .catch(() => {
          // this.$message.error("系统错误,请联系管理员!");
        });
    },
    submit() {
      const data = {
        ...this.model,
      };
      this.$refs.form.validate((valid) => {
        if (valid) {
          this.$confirm(`确认要保存吗?`, "提示", {
            confirmButtonText: "确定",
            cancelButtonText: "取消",
            type: "warning",
          })
            .then(() => {
              this.loading = true;
              if (this.id) {
                this.editRequest(data);
              } else {
                this.addRequest(data);
              }
            })
            .catch(() => {});
        } else {
          return false;
        }
      });
    },
    addRequest(data) {
      add(data)
        .then((res) => {
          this.loading = false;
          if (res.code === 700) {
            this.$message.warning(res.msg);
            return false;
          }
          this.$message.success("操作成功");
          this.handleClose(true);
        })
        .catch(() => {
          this.loading = false;
          // this.$message.error("系统错误,请联系管理员!");
        });
    },
    editRequest(data) {
      edit(data)
        .then((res) => {
          this.loading = false;
          if (res.code === 700) {
            this.$message.warning(res.msg);
            return false;
          }
          this.$message.success("操作成功");
          this.handleClose(true);
        })
        .catch(() => {
          this.loading = false;
          // this.$message.error("系统错误,请联系管理员!");
        });
    },
    handleClose(status) {
      this.$refs["form"].resetFields();
      this.model.typeConfigRecordRequests = [];
      this.$emit("update:visible", false);
      this.$emit("close", status === true ? status : false);
    },
  },
};
</script>

<style scoped lang="scss">
.title {
  text-align: center;
  font-weight: bold;
}
::v-deep .form {
  .el-descriptions__header {
    justify-content: center;
    .el-descriptions__title {
      font-weight: 100;
    }
  }
  .el-descriptions-row {
    height: 54px;
    .el-descriptions-item__cell {
      padding: 0 10px;
    }
    .el-descriptions-item__label {
      width: 140px;
      text-align: center;
    }
  }
  .el-descriptions-item__content {
    .el-form-item__content,
    .el-form-item__label {
      transform: translateY(10px);
    }
  }
  .flex {
    display: flex;
    .flex1 {
      flex: 1;
    }
  }
}
</style>
